public class MatrixTriangle {
    private int[] arr;
    private int arraysize;

    public MatrixTriangle() {
    }

    public static void main(String[] args) {
        int[][] array = {{1, 0, 0, 0}, {1, 2, 0, 0}, {2, 1, 3, 0}, {1, 2, 1, 4}};
        MatrixTriangle matrixTriangle = new MatrixTriangle();
        matrixTriangle.compress(array);
        System.out.println("================");
        System.out.print("[");
        for (int i = 0; i < matrixTriangle.arraysize; i++) {
            for (int j = 0; j <= i; j++) {
                System.out.print(matrixTriangle.getValue(i, j) + " ");
            }
        }
        System.out.print("]");

    }

    /**
     * 将下三角二维array压缩
     *
     * @param array
     */

    public void compress(int[][] array) {
        arraysize = array.length;
        //一维数组长度 n/2*（1+n）
        arr = new int[arraysize / 2 * (1 + arraysize)];
        int index = 0;
        //将二维数组非零的代入一维数组
        for (int i = 0; i < arraysize; i++) {
            for (int j = 0; j <= i; j++) {
                if (array[i][j] != 0) {
                    arr[index++] = array[i][j];
                }
            }
        }

    }


    public int getValue(int i, int j) {
        if (i < j) {
            return 0;
        } else {
            // i*（i+1）/2+j 左下三角形
            int index = i * (i + 1) / 2 + j;
            return arr[index];
        }
    }

}
